/**
 * @FileName: Send.java
 * @Package: com.rabbitmq
 * @author lig134
 * @created 2017/3/8 18:16
 * <p>
 * Copyright 2015 ziroom
 */
package com.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * <p></p>
 * publish 消息
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author lig134
 * @version 1.0
 * @since 1.0
 */
public class Send {
    public static final String EXCHANGE_NAME = "text-exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connFac = new ConnectionFactory();

        //RabbitMQ-Server安装在本机，所以直接用127.0.0.1
        connFac.setHost("master");
        connFac.setUsername("ligen");
        connFac.setPassword("ligen");
        //创建一个连接
        Connection conn = connFac.newConnection();

        //创建一个渠道
        Channel channel = conn.createChannel();

        //定义ExchangeName,第二个参数是Exchange的类型，fanout表示消息将会分列发送给多账户
        String exchangeName = "news";
        channel.exchangeDeclare(exchangeName, "fanout");
        channel.basicQos(1);

        String msg = "ligen";
        //消息持久化 MessageProperties.PERSISTENT_TEXT_PLAIN
        //发送多条信息，每条消息对应routekey都不一致
        for (int i = 0; i < 10; i++) {
//            channel.basicPublish(exchangeName, "", null, (msg).getBytes());
//            channel.basicPublish(exchangeName, msg + (i % 2), null,
//                    (msg + i).getBytes());
            channel.basicPublish(exchangeName+(i % 2), msg + (i % 2), null,
                    (msg + i).getBytes());

            System.out.println("[send] msg " + (msg + i) + " of routingKey is " + (msg + (i % 2)));
        }
        channel.close();
        conn.close();

    }

    public static void main1(String[] args) throws IOException, TimeoutException {

        ConnectionFactory connFac = new ConnectionFactory();

        //RabbitMQ-Server安装在本机，所以直接用127.0.0.1
        connFac.setHost("master");
        connFac.setUsername("ligen");
        connFac.setPassword("ligen");
        //创建一个连接
        Connection conn = connFac.newConnection();

        //创建一个渠道
        Channel channel = conn.createChannel();

        //定义ExchangeName,第二个参数是Exchange的类型，fanout表示消息将会分列发送给多账户
        String exchangeName = "news";
        channel.exchangeDeclare(exchangeName, "fanout");


        String msg = "Hello World!";

        //发送消息，这里与前面的不同，这里第一个参数不再是字符串，而是ExchangeName ，第二个参数也不再是queueName，而是空字符串
        channel.basicPublish(exchangeName, "", null, msg.getBytes());

        System.out.println("send message[" + msg + "] to exchange " + exchangeName + " success!");

        channel.close();
        conn.close();

    }
}